<template>
  <div>
    <div>
      <el-input style="width: 200px" placeholder="品牌" v-model="brand"></el-input>
      <el-input style="width: 200px; margin: 0 5px" placeholder="型号" v-model="model"></el-input>
      <el-button type="primary" @click="chargingDeviceList(1)">查询</el-button>
      <el-button type="danger" @click="resetting">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="success" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
      <el-button type="info" plain @click="exportData">批量导出</el-button>
      <el-upload action="http://localhost:8888/chargingDevice/import"
                 :headers="{ token: user.token }"
                 :show-file-list="false"
                 :on-success="handleImport"
                 style="display: inline-block; margin-left: 10px"
      >
        <el-button type="primary" plain>批量导入</el-button>
        <el-button type="primary" plain @click="importTem">下载模版</el-button>
      </el-upload>

    </div>
    <el-table :data="tableData" stripe :header-cell-style="{backgroundColor: 'aliceblue' , color: '#666'}"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" align="center"></el-table-column>
      <el-table-column prop="brand" label="品牌" align="center"></el-table-column>
      <el-table-column prop="model" label="型号" align="center"></el-table-column>
      <el-table-column prop="capacity" label="容量" align="center"></el-table-column>
      <el-table-column prop="cycle" label="循环次数" align="center"></el-table-column>
      <el-table-column prop="status" label="健康状态" align="center"></el-table-column>
      <el-table-column prop="assigned" label="电池电量" align="center"></el-table-column>
      <el-table-column prop="deviceId" label="所属设备id" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <el-button type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" plain @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 30, 40]"
          :current-page="pageIndex"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="新增充电宝信息" :visible.sync="AddDialogFormVisible" width="60%">
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="80px" style="margin-right: 20px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="品牌" maxlength="50" show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input v-model="form.model" placeholder="型号" maxlength="50" show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="容量" prop="capacity">
              <el-select v-model="form.capacity" placeholder="请选择" style="width: 100%">
                <el-option value="1000">1000mAh</el-option>
                <el-option value="5000">5000mAh</el-option>
                <el-option value="10000">10000mAh</el-option>
                <el-option value="15000">15000mAh</el-option>
                <el-option value="20000">20000mAh</el-option>
              </el-select>
              <!--              <el-input v-model="form.capacity" placeholder="容量" maxlength="50" show-word-limit></el-input>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="循环次数" prop="cycle">
              <el-input v-model="form.cycle" placeholder="循环次数" show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="健康状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择" style="width: 100%">
                <el-option value="极佳">极佳</el-option>
                <el-option value="优秀">优秀</el-option>
                <el-option value="良好">良好</el-option>
                <el-option value="建议更换">建议更换</el-option>
              </el-select>
              <!--              <el-input v-model="form.healthStatus" placeholder="健康状态" maxlength="50" show-word-limit></el-input>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电量" prop="assigned">
              <el-select v-model="form.assigned" filterable placeholder="请选择" style="width: 100%">
                <el-option
                    v-for="item in 100"
                    :key="item"
                    :label="item"
                    :value="item"
                >
                </el-option>
              </el-select>
              <!--              <el-input v-model="form.userAssigned" placeholder="电池电量" maxlength="50" show-word-limit></el-input>-->
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="所属设备" prop="deviceId">
              <el-input v-model="form.deviceId" placeholder="所属设备ID"
                        show-word-limit style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div style="text-align: center; margin-bottom: 20px">
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "ChargingDevice",
  data() {
    return {
      tableData: [], // 所有的数据
      pageIndex: 1, // 当前的页码
      pageSize: 10, // 每页显示的个数
      brand: '', // 分页查询的品牌
      model: '', // 分页查询的型号
      total: 0, // 数据的总条数
      AddDialogFormVisible: false,
      user: JSON.parse(localStorage.getItem('power-user') || '{}'), // 存储缓存
      form: {}, // 存储表单缓存
      rules: {
        brand: [{required: true, message: '请输入品牌', trigger: 'blur'},],
        assigned: [{required: true, message: '请输入电量', trigger: 'blur'},],
        // cycle: [{required: true, message: '请输入循环次数', trigger: 'blur'},],
      },
      ids: []
    }
  },
  created() {
    this.chargingDeviceList()
  },
  methods: {
    //importTem  导入模版
    importTem() {
      window.open('http://localhost:8888/file/download/充电宝信息导入摸板.xlsx')
    },
    // 批量导入数据
    handleImport(res, file, fileList) {
      if (res.code === '200') {
        this.$message.success("导入成功")
        this.chargingDeviceList(1)
      } else {
        this.$message.error(res.msg)
      }
    },
    // 批量导出数据
    exportData() {
      // 没有选择行的时候全部导出，或者根据搜索条件导出
      if (!this.ids.length) {
        window.open('http://localhost:8888/chargingDevice/export?token=' + this.user.token
            + "&brand=" + this.brand + "&capacity=" + this.model)
      } else {      // [1,2,3] => '1,2,3'
        // 把数组转为字符串
        let idStr = this.ids.join(',')
        window.open('http://localhost:8888/chargingDevice/export?token=' + this.user.token + '&ids=' + idStr)
      }
    },
    // 批量删除
    delBatch() {
      if (!this.ids.length) {
        this.$message.warning("请选择要删除的数据")
        return
      }
      // 二次确认
      this.$confirm('您确认删除这些数据吗？', '确认删除', {type: 'warning'}).then(res => {
        this.$request.delete('/chargingDevice/delete/batch', {data: this.ids}).then(res => {
          if (res.code === '200') {
            this.$message.success("操作成功")
            this.chargingDeviceList(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    handleSelectionChange(rows) { // 当前选中行的所有数据
      console.log(rows)
      this.ids = rows.map(v => v.id)
      // console.log(ids)
    },
    // 单个删除
    del(id) {
      // 二次确认
      this.$confirm('您确认删除吗？', '确认删除', {type: 'warning'}).then(res => {
        this.$request.delete('/chargingDevice/delete/' + id).then(res => {
          if (res.code === '200') {
            this.$message.success("操作成功")
            this.chargingDeviceList(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    handleAdd() { // 新增数据
      // 新增数据的时候清空数据
      this.form = {}
      // 打开弹窗
      this.AddDialogFormVisible = true
    },
    handleEdit(row) { // 编辑数据
      // 给form对象赋值，注意要深拷贝数据
      this.form = JSON.parse(JSON.stringify(row))
      // 打开弹窗
      this.AddDialogFormVisible = true
    },
    handleAvatarSuccess(response, file, fileList) {
      // 把chargingDevice的头像属性换成上传的图片的链接
      this.form.avatar = response.data
    },
    save() { // 保存按钮触发的逻辑 它会触发新增或者修改
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.$request({
            // 因为修改是从行内元素拿到的，有id，因此可以作此判断
            // 判断有没id，如果有id说明是修改的方法，如果没有则是新增的方法
            method: this.form.id ? 'POST' : 'POST',
            url: this.form.id ? '/chargingDevice/update' : '/chargingDevice/add',
            data: this.form
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('保存成功')
              this.chargingDeviceList(1)
              this.AddDialogFormVisible = false
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },

    resetting() {
      this.brand = ''
      this.model = ''
      this.chargingDeviceList()
    },
    chargingDeviceList(pageIndex) { // 分页查询
      if (pageIndex) {
        this.pageIndex = pageIndex
      }
      request.get('/chargingDevice/selectByPage', {
        params: {
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          brand: this.brand,
          model: this.model,
        }
      }).then(res => {
        if (res.code == '200') {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },
    handleCurrentChange(pageIndex) {
      // 赋值
      this.pageIndex = pageIndex
      // 调用分页查询方法
      this.chargingDeviceList()
    }
  },
}
</script>

<style scoped>
</style>